<?php

namespace App\Imports;

use App\Http\Util\Err;
use App\Http\Util\Tool;
use App\Models\AllExam;
use App\Models\Answers;
use App\Models\OperAnswers;
use App\Models\OperateCate;
use App\Models\OperScore;
use App\Models\Question;
use App\Models\Sign;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;

class ExamScoreImport implements ToCollection
{

    public $all_exam_id;
    public $errstr = '';

    public function __construct($all_exam_id)
    {
        $this->all_exam_id = $all_exam_id;
    }

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function collection(Collection $rows)
    {
        try{
            $examId = AllExam::where('id',$this->all_exam_id)->value('exam_id');
            // TODO: Implement collection() method.

            $data=json_decode(json_encode($rows),true);
            //去掉第一行的标题
            array_splice($data, 0, 1);
            $log = '';
            $all_exam_id = AllExam::where('id',$this->all_exam_id)->value('exam_id');
            //拼接字段入库
            foreach ($data as $row)
            {
                $student = Sign::where('exam_student_id',$row[4])
                    ->where('is_del',Err::DEL_SHOW)
                    ->where('all_exam_id',$this->all_exam_id)->count();
                if($student<0){
                    $this->errstr.=$row[6]."\n";
                    continue;
                }else{
                    $query['exam_student_id'] =  $row[4];
                    $query['all_exam_id'] =  $all_exam_id;
                    $query['score'] = $row[7];
                    $check = Answers::where('exam_student_id',$row[4])
                        ->where('is_del',Err::DEL_SHOW)
                        ->first();
                    if($check){
                        $check->update($query);
                    }else{
                        $query['type']= 'import';
                        $query['status'] = 2;
                        Answers::create($query);
                    }
                }
            }
        }catch (\Exception $e){
            echo $e->getMessage();
//                    Tool::logError('数据导入失败',$e->getMessage(), $file = 'lumen');
        }
    }


    public function createData($rows)
    {
        //todo
    }
}
